/********************************************************************************
 *@description: 抽奖管理  lotteryTools/lotteryManage/index
 *@author: Xhd
 *@API: 纪浩然, 抽奖模板-清悦
 *@date: 2024-01-16 13:38:43
 *@version: V1.0.0
**********************************************************************************/

import React, { Component } from 'react';
import { Modal, Switch, message, Select } from 'antd';
import TheQueryForm from '@/components/TheQueryForm';
import TheTable from '@/components/TheTable';
import ThePagination from '@/components/ThePagination';
import TheButton from '@/components/TheButton';
import store from "@/store/store";
import { apiLotteryDrawTurntablePage, apiSwitchLotteryDrawTurntable, apiFindLotteryDrawTurntableSweepstakes } from "@/request/lotteryTools";
import moment from 'moment';
import _ from 'lodash';

const Option = Select
class LotteryManage extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef();
    this.state = {
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
        },
        {
          title: "活动名称",
          dataIndex: "turntableName",
          key: "turntableName",
        },
        {
          title: "奖池类型",
          dataIndex: "turntableType",
          key: "turntableType",
          render: (text) => {
            return text === "0" ? "狗" : "猫"
          }
        },
        {
          title: "消耗类型",
          dataIndex: "consumeType",
          key: "consumeType",
          render: (text) => {
            let label = ""
            switch (text) {
              case "HHD":
                label = "哈哈豆"
                break;
              case "CB":
                label = "宠币"
                break;
              default:
                break;
            }
            return label
          }
        },
        {
          title: "单次消耗",
          dataIndex: "onceConsume",
          key: "onceConsume",
        },
        {
          title: "累计参与人数",
          dataIndex: "participationNumberCount",
          key: "participationNumberCount",
        },
        {
          title: "活动周期（天）",
          dataIndex: "activityDays",
          key: "activityDays",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "活动有效期",
          dataIndex: "activityExpirationDate",
          key: "activityExpirationDate",
        },
        {
          title: "状态",
          dataIndex: "state",
          key: "state",
          render: (text, record, index) => {
            let checked = 0
            let disabled = false
            let nowTime = moment(new Date()).format("YYYY-MM-DD")
            switch (text) {
              case "Y":
                checked = 1
                break;
              case "N":
                checked = 0
                break;
              case "E":
                checked = 0
                break;
              default:
                break;
            }
            let endTime = moment(record.activityExpirationDate.slice(11,21)).format("YYYY-MM-DD")
            if(nowTime > endTime) {
              disabled = true
            }
            return <Switch disabled={disabled} checked={checked} onClick={(value)=>this.stateChange(value, record.lotteryDrawTurntableId, index)} />
          }
        },
        {
          title: "操作",
          fixed: "right",
          width: 300,
          render: (text, record) => {
            return (
              <div>
                <TheButton
                  haspermi={["lottery:manage:detail"]}
                  onClick={() => this.createLottery("view", record.lotteryDrawTurntableId)}
                >
                  详情
                </TheButton>
                {record.state === "N" &&
                  <TheButton
                    haspermi={["lottery:manage:edit"]}
                    onClick={() => this.createLottery("edit", record.lotteryDrawTurntableId)}
                  >
                    编辑
                  </TheButton>
                }
              </div>
            );
          },
        },
      ],
      dataSource: [],
      pageData: { pageNo: 1, pageSize: 10 },
      total: 0,
      queryForm: {},
      searchOption: [
        {
          field: "turntableName",
          label: "转盘名称",
          placeholder: "请输入名称",
          required: false,
          rules: [],
          type: "Input",
          defaultValue: "",
        },
        {
          field: "turntableType",
          label: "奖池类型",
          placeholder: "请选择奖池类型",
          required: false,
          rules: [],
          type: "Select",
          options: [
            { value: "", label: "全部" },
            { value: "1", label: "猫" },
            { value: "0", label: "狗" },
          ],
          defaultValue: "",
        },
        {
          field: "time",
          label: "日期",
          placeholder: "",
          required: false,
          rules: [],
          type: "RangePicker",
          defaultValue: "",
        },
      ],
      addModelVisible: false,
      modelList: [],
      lotteryDrawTurntableId: ''
    }
  }
  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'lottery') {
      this.setState({
        queryForm,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({
          ...queryForm
        })
        this.getData()
      })
    } else {
      this.getData()
    }
  }

  getData = async (values) => {
    const { pageNo, pageSize } = this.state.pageData
    if (values && !_.isEmpty(values.time)) {
      values.activityStartTime = moment(values.time[0]).format("YYYY-MM-DD")
      values.activityEndTime = moment(values.time[1]).format("YYYY-MM-DD")
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        pageNo, pageSize, queryForm: this.state.queryForm
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'lottery',
          ...params
        }
      })
      let res = await apiLotteryDrawTurntablePage({
        pageNo, pageSize, ...this.state.queryForm
      })
      if (res.code === 0) {
        let data = res.data.map((item, key) => {
          item.index = (pageNo - 1) * pageSize + (key + 1)
          return item
        })
        this.setState({
          dataSource: data,
          total: res.totalCount
        })
      }
      await apiFindLotteryDrawTurntableSweepstakes().then((res)=>{
        if(res.code == 0){
          this.setState({
            modelList: res.data
          })
        }
      })
    })
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => this.getData())
  }
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  onFormSearch(values) {
    this.setState({
      pageData: { pageNo: 1, pageSize: this.state.pageData.pageSize }
    }, () => {
      this.getData(values)
    })
  }
  stateChange = async (value, id, index) => {
    let status = value ? "Y" : "E"
    await apiSwitchLotteryDrawTurntable({lotteryDrawTurntableId: id, state: status}).then(res=>{
      if(res.code === 0){
        if(status === "Y") {
          message.success("已启用")
        }else {
          message.success("已停用")
        }
        this.getData()
      }
    })
  } 

  addModel = () => {
    this.setState({
      addModelVisible: true
    })
  }
  modelLottery = (v) => {
    this.setState({
      lotteryDrawTurntableId: v
    })
  }

  ModelAdd = () => {
    const { lotteryDrawTurntableId } = this.state
    if(lotteryDrawTurntableId) {
      this.createLottery("addModel", lotteryDrawTurntableId)
    }else {
      React.$message({
        type: 'warning',
        content: '请选择模板创建！'
      })
    }
  }

  createLottery = (type, id) => {
    this.props.history.push(`/lotteryTools/lotteryManage/views/${type}/${id}`)
  }
  render() {
    const { columns, dataSource, pageData: { pageNo, pageSize }, total, searchOption, addModelVisible, modelList } = this.state;
    return (<div className='p-layout-box'>
      <TheQueryForm ref={(ref) => (this.queryFormRef = ref)} show={true} option={searchOption} onReset={() => this.onReset()} onGetValues={(values) => this.onFormSearch(values)} >
        <TheButton haspermi={["lottery:manage:add"]} type="primary" size="middle" onClick={() => this.createLottery("add", null)} >新增</TheButton>
        <TheButton haspermi={["lottery:manage:addModel"]} type="primary" size="middle" onClick={() => this.addModel()} disabled={dataSource.length == 0} >模板新增</TheButton>
      </TheQueryForm>
      <TheTable scroll={{ x: 'max-content', y: '63vh' }} columns={columns} dataSource={dataSource} />
      <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
      <Modal
        title='选择模板'
        open={addModelVisible}
        onCancel={()=> {this.setState({addModelVisible: false})}}
        onOk={()=>{this.ModelAdd()}}
      >
        <Select style={{width: '100%'}} onChange={(v)=>this.modelLottery(v)} >
          {modelList.map((v)=>{
            return <Option key={v.lotteryDrawTurntableId} value={v.lotteryDrawTurntableId}>{v.turntableName}</Option>
          })}
        </Select>
      </Modal>
    </div>)
  }
}

export default LotteryManage